package com.jmpt.fangbohui.ui;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.adapter.HouseSeleteMoreAdapter;
import com.jmpt.fangbohui.adapter.NewHouseListAdapter;
import com.jmpt.fangbohui.adapter.NewHouseSelectOrderAdapter;
import com.jmpt.fangbohui.adapter.NewHouseSelectPriceAdapter;
import com.jmpt.fangbohui.adapter.NewHouseSelectRegionAdapter;
import com.jmpt.fangbohui.bean.NewHouseBean;
import com.jmpt.fangbohui.helper.CommonHelper;
import com.jmpt.fangbohui.http.ApiRequest;
import com.jmpt.fangbohui.http.JsonHttpHandler;
import com.jmpt.fangbohui.ui.base.BaseHeadActivity;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.ImageLoaderHelper;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

public class BuyNewHouseListActivity extends BaseHeadActivity implements
		OnClickListener {

	private static final int SEARCH_REQUEST_CODE = 111;
	private static final String TAG = "BuyNewHouseListActivity.java";
	private Button btn_locationSelete;
	private Button btn_priceSelete;
	private Button btn_orderSelete;
//	private Button btn_moreSelete;
	private PullToRefreshListView plv_houseList;
	private RelativeLayout mLoading;
	private ViewStub vs_seleteArea;
	private NewHouseListAdapter mHouseListAdapter;
	private boolean isFirstLoad;
	private boolean isNoMore;
	private String currSearchKey;
	private NewHouseSelectRegionAdapter mSeleteRegionAdapter;
	private NewHouseSelectPriceAdapter mSeletePriceAdapter;
	private NewHouseSelectOrderAdapter mSelectOrderAdapter;
	//more
//	private HouseSeleteMoreAdapter mSelectMoreLeftAdapter;
//	private HouseSeleteMoreRightAdapter mSeleteMoreRightAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_newhouse_list);
		// 设置标题
		showTitle("买新房");
		// 设置返回键
		showBackButton(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		showRightImageButton(R.drawable.ic_home_search,
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						 Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
						 intent.putExtra(SearchActivity.CURR_KEY, currSearchKey);
						 startActivityForResult(intent,SEARCH_REQUEST_CODE);
					}
				});

		assignViews();
		initView();
	}

	private void initView() {
//		addMenuItem(R.drawable.btn_main_home,"主页");
//		addMenuItem(R.drawable.btn_main_home,"搜索1");
//		addMenuItem(R.drawable.btn_main_home,"搜索2");
		mHouseListAdapter = new NewHouseListAdapter(this);
		plv_houseList.setAdapter(mHouseListAdapter);
		plv_houseList.setMode(PullToRefreshBase.Mode.BOTH);
		plv_houseList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> adapterView,
							View view, int i, long l) {
					     try {
							//显示房屋详情
							 Intent intent = new Intent(BuyNewHouseListActivity.this,NewHouseDetailActivity.class);
							 intent.putExtra(NewHouseDetailActivity.HOUSE_ID, mHouseListAdapter.houseList.get(i - 1).id);
							 intent.putExtra(NewHouseDetailActivity.HOUSE_TITLE, mHouseListAdapter.houseList.get(i -1 ).title);
							 startActivity(intent);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
		
		plv_houseList
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						fistLoad();
					}
					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						if(isNoMore){
							ToastHelper.ShowToast("没有更多数据了", getApplicationContext());
							plv_houseList.onRefreshComplete();
							return;
						}
						// 加载更多
						loadMore();
					}
				});

		plv_houseList.setOnScrollListener(new PauseOnScrollListener(ImageLoaderHelper.getImageLoader(), true, true));  
		
		mSeleteRegionAdapter = new NewHouseSelectRegionAdapter(this);
		mSeleteRegionAdapter.data = CommonHelper.getNewHouseRegionBeans();
		mSeletePriceAdapter = new NewHouseSelectPriceAdapter(this);
		mSeletePriceAdapter.data = CommonHelper.getNewHousePriceBeans();
		mSelectOrderAdapter = new NewHouseSelectOrderAdapter(this);
		mSelectOrderAdapter.data = CommonHelper.getNewHouseOrderBeans();
		
		//more
		//初次化更多筛选分类列表数据 适配器
		//mSelectMoreLeftAdapter = new HouseSeleteMoreAdapter(this);
		//TODO 获取新房筛选条件数据
		//mSelectMoreLeftAdapter.data = CommonHelper.getNewHouseMoreCategoryBeans();
				
		//初次化更多筛选分类列表数据 适配器
//		mSeleteMoreRightAdapter = new HouseSeleteMoreRightAdapter(this, null);
		
		initSeleteView();

		btn_locationSelete.setOnClickListener(this);
		btn_priceSelete.setOnClickListener(this);
		btn_orderSelete.setOnClickListener(this);
//		btn_moreSelete.setOnClickListener(this);

		fistLoad();

	}

	private void fistLoad() {
		isNoMore = false;
		load(true);
	}

	private void assignViews() {

		btn_locationSelete = (Button) findViewById(R.id.btn_newhouse_list_locationSelete);
		btn_priceSelete = (Button) findViewById(R.id.btn_newhouse_list_priceSelete);
		btn_orderSelete = (Button) findViewById(R.id.btn_newhouse_list_orderSelete);
//		btn_moreSelete = (Button) findViewById(R.id.btn_newhouse_list_moreSelete);

		plv_houseList = (PullToRefreshListView) findViewById(R.id.plv_newhouse_list_content);
		mLoading = (RelativeLayout) findViewById(R.id.rel_newhouse_list_loading);
		vs_seleteArea = (ViewStub) findViewById(R.id.vs_newhouse_list_seleteArea);
		// 查找筛选区域视图
		v_seleteArea = vs_seleteArea.inflate();
		v_seleteArea.setVisibility(View.INVISIBLE);
		assignSeleteViews(v_seleteArea);
	}

	private ImageView iv_seleteArea;
	private ListView lv_seleteArea_left;
	private ListView lv_seleteArea_right;
	private View v_seleteArea;
	protected int mCurrenLocationIndex;
	protected int mCurrenHousePriceIndex;
	protected int mCurrenOrderIndex;
	
//	private int mCurrenMoreLeftIndex;
	//一页显示10条数据
	private int limit = Constants.limit.NEW_HOUSE_PAGE_LIMIT;

	private void assignSeleteViews(View view) {
		iv_seleteArea = (ImageView) view
				.findViewById(R.id.iv_house_group_select_background);
		lv_seleteArea_left = (ListView) view
				.findViewById(R.id.lv_house_group_select_left);
		lv_seleteArea_right = (ListView) view
				.findViewById(R.id.lv_house_group_select_right);

	}

	public void initSeleteView() {
		lv_seleteArea_left
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						if (lv_seleteArea_left.getAdapter() instanceof NewHouseSelectRegionAdapter) {

							mCurrenLocationIndex = position;
							for (int i = 0; i < mSeleteRegionAdapter.data
									.size(); i++) {
								mSeleteRegionAdapter.data.get(i).isSelete = false;
							}
							mSeleteRegionAdapter.data.get(position).isSelete = true;
							mSeleteRegionAdapter.notifyDataSetChanged();
							hideSeleteArea();
							fistLoad();
							refreshLocationButtonName();
						}
						if (lv_seleteArea_left.getAdapter() instanceof NewHouseSelectPriceAdapter) {
							mCurrenHousePriceIndex = position;
							for (int i = 0; i < mSeletePriceAdapter.data.size(); i++) {
								mSeletePriceAdapter.data.get(i).isSelete = false;
							}
							mSeletePriceAdapter.data.get(position).isSelete = true;
							mSeletePriceAdapter.notifyDataSetChanged();
							hideSeleteArea();
							fistLoad();
							refreshPriceButtonName();
						}
						if (lv_seleteArea_left.getAdapter() instanceof NewHouseSelectOrderAdapter) {
							mCurrenOrderIndex = position;
							for (int i = 0; i < mSelectOrderAdapter.data.size(); i++) {
								mSelectOrderAdapter.data.get(i).isSelete = false;
							}
							mSelectOrderAdapter.data.get(position).isSelete = true;
							mSelectOrderAdapter.notifyDataSetChanged();
							hideSeleteArea();
							fistLoad();
							refreshOrderButtonName();
						}
						
						//more selete
						/*if (lv_seleteArea_left.getAdapter() instanceof HouseSeleteMoreAdapter) {
							mCurrenMoreLeftIndex= position; 
							if (mSelectMoreLeftAdapter.data.get(position).values == null 
									|| mSelectMoreLeftAdapter.data.get(position).values.size() == 0) {
		                        for (int i = 0; i < mSelectMoreLeftAdapter.data.size(); i++) {
		                        	mSelectMoreLeftAdapter.data.get(i).isSelete = false;
		                        	mSelectMoreLeftAdapter.data.get(i).childSelete = -1;
		                        }
		                        mSelectMoreLeftAdapter.data.get(position).isSelete = true;
		                        mSelectMoreLeftAdapter.notifyDataSetChanged();
		                        hideSeleteArea();
		                        fistLoad();
		                    } else {
		                    	//如果有子条件可选  显示右边选择区
		                    	for (int i = 0; i < mSelectMoreLeftAdapter.data.size(); i++) {
		                    		mSelectMoreLeftAdapter.data.get(i).isSelete = false;
								}
		                    	mSelectMoreLeftAdapter.data.get(position).isSelete = true;
		                    	mSeleteMoreRightAdapter.data = mSelectMoreLeftAdapter.data.get(position);
		                    	mSelectMoreLeftAdapter.notifyDataSetChanged();
		                    	mSeleteMoreRightAdapter.notifyDataSetChanged();
		                    }
						}*/
					}
				});

		/*lv_seleteArea_right
		.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				for (int i = 0; i < mSelectMoreLeftAdapter.data.size(); i++) {
					if (mSelectMoreLeftAdapter.data.get(i) == mSeleteMoreRightAdapter.data) {
						mCurrenMoreLeftIndex = i;
						mSelectMoreLeftAdapter.data.get(i).isSelete = true;
					} else {
						mSelectMoreLeftAdapter.data.get(i).isSelete = false;
					}
				}
				
				mSeleteMoreRightAdapter.data.childSelete = position;
				
				mSelectMoreLeftAdapter.notifyDataSetChanged();
				hideSeleteArea();
				fistLoad();
			}
		});*/
		
		iv_seleteArea.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				hideSeleteArea();
			}
		});
	}

	private void refreshOrderButtonName() {
		if(mCurrenOrderIndex == 0){
			btn_orderSelete
			.setText("排序");
		}else{
			btn_orderSelete
			.setText(mSelectOrderAdapter.data.get(mCurrenOrderIndex).name);
		}
		
	}

	protected void refreshPriceButtonName() {
		if(mCurrenHousePriceIndex == 0){
			btn_priceSelete.setText("价格");
		}else{
			btn_priceSelete
			.setText(mSeletePriceAdapter.data.get(mCurrenHousePriceIndex).PriceName);
		}
	}

	protected void refreshLocationButtonName() {
		if(mCurrenLocationIndex == 0){
			btn_locationSelete.setText("区域");
		}else{
			btn_locationSelete.setText(mSeleteRegionAdapter.data
					.get(mCurrenLocationIndex).ZoneName);
		}
	}

	/**
	 * 隐藏条件筛选区
	 */
	private void hideSeleteArea() {
		ObjectAnimator animator = ObjectAnimator.ofFloat(lv_seleteArea_left,
				"translationY", 0, -lv_seleteArea_left.getHeight());
		animator.addListener(new Animator.AnimatorListener() {
			@Override
			public void onAnimationStart(Animator animation) {

			}

			@Override
			public void onAnimationEnd(Animator animation) {
				v_seleteArea.setVisibility(View.INVISIBLE);
			}

			@Override
			public void onAnimationCancel(Animator animation) {

			}

			@Override
			public void onAnimationRepeat(Animator animation) {

			}
		});

		ObjectAnimator translationRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "translationY", 0,-lv_seleteArea_right.getHeight());
		ObjectAnimator alphaArea = ObjectAnimator.ofFloat(iv_seleteArea, "alpha", 1f, 0f);
		ObjectAnimator alphaRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "alpha", 1f, 0f);
		AnimatorSet set = new AnimatorSet();
		set.playTogether(animator,translationRight,alphaArea,alphaRight);
		set.start();
	}
	
	 private void showSeleteArea() {

	        ViewTreeObserver vto2 = lv_seleteArea_left.getViewTreeObserver();

	        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
	            @Override
	            public void onGlobalLayout() {
	            	lv_seleteArea_left.getViewTreeObserver().removeGlobalOnLayoutListener(this);
	                int height = lv_seleteArea_left.getHeight();
	                int width = lv_seleteArea_left.getWidth();
	                DebugLog.e("height: " + height);
	                DebugLog.e("width: " + width);
	                if (lv_seleteArea_left.getAdapter() instanceof HouseSeleteMoreAdapter) {
//	                    ViewGroup.LayoutParams layoutParams = lv_seleteArea_right.getLayoutParams();
//	                    layoutParams.height = height;
//	                    lv_seleteArea_right.setLayoutParams(layoutParams);
	                    lv_seleteArea_right.setVisibility(View.VISIBLE);
	                } else {
	                	lv_seleteArea_right.setVisibility(View.GONE);
	                }
	                
	                ObjectAnimator animatorLeft = ObjectAnimator.ofFloat(lv_seleteArea_left, "translationY", -lv_seleteArea_left.getHeight(), 0);

	                animatorLeft.addListener(new Animator.AnimatorListener() {
	                    @Override
	                    public void onAnimationStart(Animator animation) {

	                        v_seleteArea.setVisibility(View.VISIBLE);

	                    }

	                    @Override
	                    public void onAnimationEnd(Animator animation) {

	                    }

	                    @Override
	                    public void onAnimationCancel(Animator animation) {

	                    }

	                    @Override
	                    public void onAnimationRepeat(Animator animation) {

	                    }
	                });
	                ObjectAnimator alphaArea = ObjectAnimator.ofFloat(iv_seleteArea, "alpha", 0f, 1f);
	                ObjectAnimator translationRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "translationY", -lv_seleteArea_right.getHeight(), 0);
	                ObjectAnimator alphaRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "alpha", 0f, 1f);
	                AnimatorSet set = new AnimatorSet();
	                set.playTogether(animatorLeft,translationRight,alphaArea,alphaRight);
	                set.start();
	            }
	        });
	    }

	private void load(boolean isFrist) {
		isFirstLoad = isFrist;
		
		String orderType = "";
		int zoneId = 0;
		String price = "";
		if (mCurrenOrderIndex > 0) {
			orderType = mSelectOrderAdapter.data.get(mCurrenOrderIndex).type;
		}
		if (mCurrenLocationIndex > 0) {
			zoneId = mSeleteRegionAdapter.data.get(mCurrenLocationIndex).ZoneID;
		}
		
		if (mCurrenHousePriceIndex > 0) {
			price = mSeletePriceAdapter.data.get(mCurrenHousePriceIndex).PriceID;
		}
		int page;
		//是否是第一次加载 | 或者更改筛选条件后重新加载
		if (isFirstLoad) {
			page = 1;
		} else {
			//追加数据
			page = mHouseListAdapter.getCount() / limit  + 1;
		}
		addRequestHandle(ApiRequest.getNewHouseListData(this,currSearchKey, zoneId, price, orderType, page, limit,
				new HttpNewHouseListHandler(this,false)));
		
		DebugLog.i("zoneId:" + zoneId);
		DebugLog.i("orderType:" + orderType);
		DebugLog.i("PriceID:" + price);
		DebugLog.i("page:" + page);
	}

	private void loadMore() {
		load(false);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_newhouse_list_locationSelete:
			if (v_seleteArea.getVisibility() == View.VISIBLE) {
				if (lv_seleteArea_left.getAdapter() instanceof NewHouseSelectRegionAdapter) {
					hideSeleteArea();
				} else {                 
					lv_seleteArea_left.setAdapter(mSeleteRegionAdapter);
					mSeleteRegionAdapter.notifyDataSetChanged();
					lv_seleteArea_right.setVisibility(View.GONE);
				}
			} else {
				lv_seleteArea_left.setAdapter(mSeleteRegionAdapter);
				mSeleteRegionAdapter.notifyDataSetChanged();
				lv_seleteArea_right.setVisibility(View.GONE);
				showSeleteArea();
			}

			break;
		case R.id.btn_newhouse_list_priceSelete:
			if (v_seleteArea.getVisibility() == View.VISIBLE) {
				if (lv_seleteArea_left.getAdapter() instanceof NewHouseSelectPriceAdapter) {
					hideSeleteArea();
				} else {
					lv_seleteArea_left.setAdapter(mSeletePriceAdapter);
					mSeletePriceAdapter.notifyDataSetChanged();
					lv_seleteArea_right.setVisibility(View.GONE);
				}
			} else {
				lv_seleteArea_left.setAdapter(mSeletePriceAdapter);
				mSeletePriceAdapter.notifyDataSetChanged();

				showSeleteArea();
			}

			break;

		case R.id.btn_newhouse_list_orderSelete:
			if (v_seleteArea.getVisibility() == View.VISIBLE) {
				if (lv_seleteArea_left.getAdapter() instanceof NewHouseSelectOrderAdapter) {
					hideSeleteArea();
				} else {
					lv_seleteArea_left.setAdapter(mSelectOrderAdapter);
					mSelectOrderAdapter.notifyDataSetChanged();
					lv_seleteArea_right.setVisibility(View.GONE);
				}
			} else {
				lv_seleteArea_left.setAdapter(mSelectOrderAdapter);
				mSelectOrderAdapter.notifyDataSetChanged();

				showSeleteArea();
			}
			break;
			
		/*case R.id.btn_newhouse_list_moreSelete:
			if (v_seleteArea.getVisibility() == View.VISIBLE) {
				if (lv_seleteArea_left.getAdapter() instanceof HouseSeleteMoreAdapter) {
					hideSeleteArea();
				} else {
					lv_seleteArea_left.setAdapter(mSelectMoreLeftAdapter);
					mSelectMoreLeftAdapter.notifyDataSetChanged();
					lv_seleteArea_right.setVisibility(View.VISIBLE);
					lv_seleteArea_right.setAdapter(mSeleteMoreRightAdapter);
					mSeleteMoreRightAdapter.data = mSelectMoreLeftAdapter.data.get(mCurrenMoreLeftIndex);
					mSeleteMoreRightAdapter.notifyDataSetChanged();
				}
			} else {
				lv_seleteArea_left.setAdapter(mSelectMoreLeftAdapter);
				mSelectMoreLeftAdapter.notifyDataSetChanged();
				lv_seleteArea_right.setVisibility(View.VISIBLE);
				lv_seleteArea_right.setAdapter(mSeleteMoreRightAdapter);
				mSeleteMoreRightAdapter.data = mSelectMoreLeftAdapter.data.get(mCurrenMoreLeftIndex);
				mSeleteMoreRightAdapter.notifyDataSetChanged();

				showSeleteArea();
			}
			break;*/
		}
	}
	
	
	class HttpNewHouseListHandler extends JsonHttpHandler {

		public HttpNewHouseListHandler(Context context, boolean fromCache) {
			super(context, fromCache);
		}

		public HttpNewHouseListHandler(Context context) {
			super(context);
		}

		@Override
		public void onStart() {
			if (isFirstLoad) {
				//mLoading.setVisibility(View.VISIBLE);
				setShowProgressDialog("正在加载中...");
//				plv_houseList.setRefreshing(true);
			} else {
				//增加加载更多
				plv_houseList.setRefreshing(true);
			}
			super.onStart();
		}

		@Override
		public void onFinish() {
			super.onFinish();
			plv_houseList.onRefreshComplete();
		}
		
		@Override
		public void onCacheDo(String cache) {
			paseNewHouseData(cache);
		}

		@Override
		public void onDo(String response) {
			super.onDo(response);
			paseNewHouseData(response);
		}

		public void paseNewHouseData(String response) {
			plv_houseList.onRefreshComplete();
			try {
				List<NewHouseBean> entities = new Gson().fromJson(response,
						new TypeToken<List<NewHouseBean>>() {}.getType());
				if (isFirstLoad) {
					mHouseListAdapter.houseList.clear();
				}
				//获取回来的数据小于每页的数据  则说明没有更多数据了
				if (entities == null || entities.size() < limit) {
					//只能刷新 ， 不可加载更多
					plv_houseList.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
					isNoMore = true; //无更多数据了
				}else{
					plv_houseList.setMode(PullToRefreshBase.Mode.BOTH);
					DebugLog.i("entities.size():" + entities.size());
				}
				
				if(entities != null ){
					mHouseListAdapter.houseList.addAll(entities);
				}
				
				mHouseListAdapter.notifyDataSetChanged();
				
				if(isFirstLoad){
					plv_houseList.getRefreshableView().setSelection(0);
				}
				
				DebugLog.i("mAdapter.getCount():" + mHouseListAdapter.getCount());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == SEARCH_REQUEST_CODE && resultCode == RESULT_OK && data != null){
			String stringExtra = data.getStringExtra("search_key");
			currSearchKey = stringExtra;
			
			if(!TextUtils.isEmpty(currSearchKey)){
				showTitle("搜索 \"" + currSearchKey + "\"");
			}else{
				showTitle("买新房");
			}
			
			fistLoad();
			
			return;
		}
	}
	
	@Override
	public void onBackPressed() {
		if(v_seleteArea.getVisibility() == View.VISIBLE){
			hideSeleteArea();
			return;
		}
		super.onBackPressed();
	}

}
